import DB from '@/utils/sqlite.js';
import { formatDate, buildWhereClause, sortByDate, safeFixed } from '@/utils/common.js';

/**
 * 获取养车记录
 * 
 * @param {number} carId - 车辆ID
 * @param {string|number} [year='全部'] - 年份筛选
 * @returns {Promise<Object>} 包含费用记录、总费用和分类统计的数据
 */
export const getExpenseRecords = async (carId, year = '全部') => {
  try {
    const where = buildWhereClause(carId, year);
    const records = await DB.getList('expense_records', where, {}, 'date DESC');

    // 格式化数据
    const formattedRecords = sortByDate(records).map(record => ({
      id: record.id,
      car_id: record.car_id,
      mileage: record.mileage || 0,
      note: record.note || '',
      amount: safeFixed(record.amount),
      date: formatDate(record.date),
      type: record.type || '其他'
    }));

    // 计算总费用
    const expenseTotalCosts = formattedRecords.reduce(
      (sum, record) => sum + parseFloat(record.amount || 0),
      0
    );

    // 按类型统计费用
    const typeStatisticsMap = {};
    formattedRecords.forEach(record => {
      if (!record.type || isNaN(record.amount) || record.amount <= 0) return;
      typeStatisticsMap[record.type] = (typeStatisticsMap[record.type] || 0) + parseFloat(record.amount);
    });

    // 生成图表数据
    const expenseTypeStatistics = Object.entries(typeStatisticsMap)
      .map(([type, value]) => ({
        name: type,
        value: parseFloat(value)
      }))
      .sort((a, b) => b.value - a.value);

    return {
      expenseRecords: formattedRecords,
      expenseTotalCosts: safeFixed(expenseTotalCosts),
      expenseTypeStatistics
    };
  } catch (error) {
    console.error('获取养车记录失败:', error);
    return {
      expenseRecords: [],
      expenseTotalCosts: '0.00',
      expenseTypeStatistics: []
    };
  }
};

/**
 * 根据ID获取养车记录
 * 
 * @param {number} id - 记录ID
 * @returns {Promise<Object>} 养车记录数据
 */
export const getExpenseRecordById = async (id) => {
  try {
    const record = await DB.getOneById('expense_records', id);
    if (record) {
      return {
        id: record.id,
        car_id: record.car_id,
        date: formatDate(record.date),
        amount: safeFixed(record.amount),
        type: record.type || '其他',
        mileage: record.mileage || '',
        note: record.note || ''
      };
    }
    return null;
  } catch (error) {
    console.error('获取养车记录失败:', error);
    throw error;
  }
};

/**
 * 添加养车记录
 * 
 * @param {Object} record - 养车记录数据
 * @returns {Promise<boolean>} 是否添加成功
 */
export const addExpenseRecord = async (record) => {
  try {
    await DB.save('expense_records', record);
    return true;
  } catch (error) {
    console.error('添加养车记录失败:', error);
    return false;
  }
};

/**
 * 更新养车记录
 * 
 * @param {number} id - 记录ID
 * @param {Object} record - 要更新的记录数据
 * @returns {Promise<boolean>} 是否更新成功
 */
export const updateExpenseRecord = async (id, record) => {
  try {
    await DB.updateById('expense_records', record, id);
    return true;
  } catch (error) {
    console.error('更新养车记录失败:', error);
    return false;
  }
};

/**
 * 删除养车记录
 * 
 * @param {number} id - 记录ID
 * @returns {Promise<boolean>} 是否删除成功
 */
export const deleteExpenseRecord = async (id) => {
  try {
    await DB.deleteById('expense_records', id);
    return true;
  } catch (error) {
    console.error('删除养车记录失败:', error);
    return false;
  }
};